package cn.ctvonline.android.kaopu.widget.view;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.widget.TextView;

import cn.ctvonline.android.kaopu.R;
import cn.ctvonline.android.kaopu.base.util.ToastUtil;

/**
 * Created by dujian on 15/11/16.
 */
public class PullToRefershRecycleView extends SwipeRefreshLayout {
    static final String TAG = "PullToRefershView";
    private RecyclerView mRecycleView;
    private Context mContext;
    private RecyclerView.Adapter rvAdapter;
    private LinearLayoutManager mLayoutManager;
    private TextView bottomView;
    private boolean canBottomVisiable;
    private Handler handler;
    static final int REFERSH_DATA_OK = 0x01;

    public PullToRefershRecycleView(Context context) {
        this(context, null);
    }

    public PullToRefershRecycleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        mRecycleView = new RecyclerView(mContext);
        mLayoutManager = new LinearLayoutManager(mContext);
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecycleView.setLayoutManager(mLayoutManager);
        bottomView = new TextView(context);
        SwipeRefreshLayout.LayoutParams recycleLp = new SwipeRefreshLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        SwipeRefreshLayout.LayoutParams bottomLp = new SwipeRefreshLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        bottomView.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
        bottomView.setText("上拉加载更多");
        addView(bottomView, 0, bottomLp);
        setProgressViewOffset(false, 0, 100);
        setColorSchemeColors(R.color.colorPrimary, R.color.colorPrimaryDark, android.R.color.holo_orange_light);
        setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(3 * 1000);
                            handler.sendEmptyMessage(REFERSH_DATA_OK);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
        addView(mRecycleView, 1, recycleLp);
        initRecycleView();
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                setRefreshing(false);
                switch (msg.what) {
                    case REFERSH_DATA_OK: {
                    }
                    break;
                }
            }
        };
    }

    private void initRecycleView() {
        mRecycleView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_DRAGGING:
                        Log.i(TAG, "newState=SCROLL_STATE_DRAGGING");
                        if (canBottomVisiable) {
                            requestDisallowInterceptTouchEvent(true);
                        }
                        break;
                    case RecyclerView.SCROLL_STATE_IDLE:
                        Log.i(TAG, "newState=SCROLL_STATE_IDLE");
                        break;
                    case RecyclerView.SCROLL_STATE_SETTLING:
                        Log.i(TAG, "newState=SCROLL_STATE_SETTLING");
                        break;
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int itemCount = mLayoutManager.getItemCount();
                int childCount = mLayoutManager.getChildCount();
                int lastPosition = mLayoutManager.findFirstVisibleItemPosition();
                Log.i(TAG, "lastPosition=" + lastPosition + ", childCount=" + childCount + ", itemCount=" + itemCount);
                canBottomVisiable = lastPosition > 0 && lastPosition + childCount >= itemCount && !isRefreshing();
                Log.i(TAG, "onScrolled dx=" + dx + ", dy=" + dy + ", canBottomVisiable=" + canBottomVisiable);
            }
        });
    }

    private int downY;
    private int downX;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        Log.i(TAG, "dispatchTouchEvent canBottomVisiable=" + canBottomVisiable);
        if (canBottomVisiable) {
            int action = ev.getAction();
            switch (action) {
                case MotionEvent.ACTION_DOWN: {
                    downX = (int) ev.getX();
                    downY = (int) ev.getY();
                }
                break;
                case MotionEvent.ACTION_MOVE: {
                    int deltaX = (int) ev.getX() - downX;
                    int deltaY = (int) ev.getY() - downY;
                    Log.i(TAG, "ActionMove deltaY=" + deltaY + ", deltaX=" + deltaX + ",Y=" + mRecycleView.getY());
                    if (Math.abs(deltaY) > Math.abs(deltaX)
                            && Math.abs(deltaY) > 10
                            && deltaY < 0
                            && Math.abs(deltaY + mRecycleView.getY()) < 100) {
                        mRecycleView.setY(deltaY + mRecycleView.getY());
                    }
                }
                break;
                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_UP: {
                    Log.i(TAG, "mRecycleView y = " + mRecycleView.getY());
                    animateBack();
                }
                break;
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return super.onTouchEvent(ev);
    }

    private void animateBack() {
        float y = mRecycleView.getY();
        ValueAnimator animator = ValueAnimator.ofFloat(y, 0);
        animator.setDuration(300);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mRecycleView.setY((float) animation.getAnimatedValue());
            }
        });
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationCancel(Animator animation) {
                super.onAnimationCancel(animation);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                doLoadData();
            }
        });
    }

    private void doLoadData() {
        ToastUtil.show(mContext, "loadData");
    }

    public void setRvAdapter(RecyclerView.Adapter Adapter) {
        this.rvAdapter = Adapter;
        mRecycleView.setAdapter(rvAdapter);
        rvAdapter.notifyDataSetChanged();
    }

    public void setLayoutManager(LinearLayoutManager layoutManager) {
        this.mLayoutManager = layoutManager;
        mRecycleView.setLayoutManager(mLayoutManager);
    }
}
